package com.ovt.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
 * 鏁版嵁搴撹繛鎺ヤ笌鍏抽棴宸ュ叿绫汇�
 * @author 鍖楀ぇ闈掗笩
 */
public class BaseDao {
	protected Connection conn;
	protected PreparedStatement pstmt;
	protected ResultSet rs;
	/**
	 * 鑾峰彇鏁版嵁搴撹繛鎺ュ璞°�
	 */
	public Connection getConnection() {
		// 鑾峰彇杩炴帴骞舵崟鑾峰紓甯�
		try {
			Class.forName("com.mysql.jdbc.Driver");// 鍔ㄦ�鍔犺浇mysql椹卞姩
			String url = "jdbc:mysql://localhost:3306/test?"
					+ "user=root&password=123456&useUnicode=true&characterEncoding=UTF8";
			//鍒涘缓杩炴帴
			conn = DriverManager.getConnection(url);		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	/**
	 * 鍏抽棴鏁版嵁搴撹繛鎺ャ�
	 * @param conn 鏁版嵁搴撹繛鎺�
	 * @param stmt Statement瀵硅薄
	 * @param rs 缁撴灉闆�
	 */
	public void closeAll(Connection conn, Statement stmt, ResultSet rs) {
		// 鑻ョ粨鏋滈泦瀵硅薄涓嶄负绌猴紝鍒欏叧闂�
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 鑻tatement瀵硅薄涓嶄负绌猴紝鍒欏叧闂�
		if (stmt != null) {
			try {
				stmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 鑻ユ暟鎹簱杩炴帴瀵硅薄涓嶄负绌猴紝鍒欏叧闂�
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 澧炪�鍒犮�鏀规搷浣�
	 * @param sql sql璇彞
	 * @param prams 鍙傛暟鏁扮粍
	 * @return 鎵ц缁撴灉
	 */
	public int exceuteUpdate(String sql,Object...prams){
		int result=0;
		conn=this.getConnection();
		try {
			pstmt=conn.prepareStatement(sql);
			for(int i=0;i<prams.length;i++){
				pstmt.setObject(i+1, prams[i]);	
			}
			result=pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(conn, pstmt, rs);
		}
		return result;
	}
}
